//
//  ZFBCycleImageView.m
//  12-支付宝(code)
//
//  Created by apple on 16/10/26.
//  Copyright © 2016年 ly. All rights reserved.
//

#import "ZFBCycleImageView.h"
#import "Masonry.h"
#import "ZFBCycleImageCell.h"
#import "ZFBCycleImageLayout.h"

#define imagesCountHalf 1
@interface ZFBCycleImageView()
@property (nonatomic, strong) UIPageControl *pageC;
@property (nonatomic, strong) UICollectionView *imageUCV;
@property (nonatomic, weak) NSTimer *timer;
@end
static NSString *cellID = @"imageCell";
@implementation ZFBCycleImageView
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}
/// 搭建界面
- (void)setupUI{
//    for (int i = 0; i < 5; i++) {
//        UIImage *image = [UIImage imageNamed:self.imagesArr[i]];
//    }
    UIImage *img01 = [UIImage imageNamed:@"page_01"];
    UIImage *img02 = [UIImage imageNamed:@"page_02"];
    
    NSArray *imgArr = @[img01,img02];
    self.imagesArr = imgArr;
    
    ZFBCycleImageLayout *layout = [ZFBCycleImageLayout new];
    //图片collectionView
    UICollectionView *imageUCV = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    //添加视图
    [self addSubview:imageUCV];
    //属性赋值
    self.imageUCV = imageUCV;
    
    //布局
    [imageUCV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    //设置代理和数据源
    imageUCV.delegate = self;
    imageUCV.dataSource = self;
    //注册cell
    [imageUCV registerClass:[ZFBCycleImageCell class] forCellWithReuseIdentifier:cellID];
    //设置分页
    imageUCV.pagingEnabled = YES;
    //设置横竖滚动条失效
    imageUCV.showsVerticalScrollIndicator = NO;
    imageUCV.showsHorizontalScrollIndicator = NO;
    //设置消除弹簧效果,使用户不会看到黑色区域
    imageUCV.bounces = NO;
    
    //设置分页按钮
    UIPageControl *pageC = [UIPageControl new];
    [self addSubview:pageC];
    self.pageC = pageC;
    pageC.currentPageIndicatorTintColor = [UIColor whiteColor];
    pageC.pageIndicatorTintColor = [UIColor grayColor];
    
    //设置图片
    [pageC setValue:[UIImage imageNamed:@"myt1"] forKey:@"pageImage"];
    [pageC setValue:[UIImage imageNamed:@"myt2"] forKey:@"currentPageImage"];

    //设置自动布局
    [pageC mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.centerX.equalTo(self);
    }];
    
    //设置定时滚动
    [self setTime];
}
//设置图片数组
-(void)setImagesArr:(NSArray *)imagesArr{
    _imagesArr = imagesArr;
    //设置pageCtr的总页数
    _pageC.numberOfPages = imagesArr.count;
}

//定时滚动方法
-(void)setTime{
    //延时执行方法
    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
    //定时滚动方法添加到commonModes
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
    //设置属性
    self.timer = timer;
}
//自动滚动方法
-(void)autoScroll{
    //设置下一页的坐标x的偏移量 加上图片宽度
    CGFloat offsetX = self.imageUCV.contentOffset.x + self.imageUCV.bounds.size.width;
    //设置contentOffset 偏移量
    
    [self makeTransition];
    
    [self.imageUCV setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}
//回滚方法
-(void)scrollBack{
    //当前是第几张图
    int count = self.imageUCV.contentOffset.x / self.imageUCV.bounds.size.width;
    //如果是第一张图片
    if (count == 0) {
        //要跳到中间的第一张图片
        NSIndexPath *curIndexPath = [NSIndexPath indexPathForItem:0 inSection:imagesCountHalf];
        [self.imageUCV scrollToItemAtIndexPath:curIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
     //如果是最后一张图片
    }else if (count == imagesCountHalf * 2 *self.imagesArr.count -1){
        //要跳到中间的最后一张图片
        NSIndexPath *curIndexPath = [NSIndexPath indexPathForItem:self.imagesArr.count - 1 inSection:imagesCountHalf - 1];
        [self.imageUCV scrollToItemAtIndexPath:curIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
}

#pragma mark-<UICollectionViewDelegate>
//滚动过程中
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //求坐标x的偏移量
    int count = round(scrollView.contentOffset.x / scrollView.bounds.size.width);
    //求第几张图
    //int index = count % self.imagesArr.count;
    //设置当前页的pageController
    //self.pageC.currentPage = index;
}
//停止滚动后调用方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self scrollBack];
}
//动画结束
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self scrollBack];
}
//开始拖拽
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //设置定时器开启时间为很久很久以后
    self.timer.fireDate = [NSDate distantFuture];
}
//结束拖拽
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //设置定时器开启时间为2秒后
    self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
}

#pragma mark
#pragma mark - layoutSubViews
//布局子控件,子视图,初始化初始位置
//-(void)layoutSubviews{
//    [super layoutSubviews];
//    //获得初始位置
//    NSIndexPath *curIndexPath = [NSIndexPath indexPathForItem:0 inSection:imagesCountHalf];
//    //赋值为初始位置
//    [self.imageUCV scrollToItemAtIndexPath:curIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
//}


#pragma mark-<UICollectionViewDataSource>
//组数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    //分组
    return 2 * imagesCountHalf;
}
//组中图片总数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //图片数组总数
    return self.imagesArr.count;
}
//设置cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //自定义cell
    ZFBCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    //加载每一张图片
    cell.image = self.imagesArr[indexPath.item];
    //返回cell
    return cell;
}
//TODO
#pragma mark - public methods
- (void)releaseTimer{
    //使定时器失效
    [self.timer invalidate];
}

- (void)removeFromSuperview{
    [super removeFromSuperview];
    [self releaseTimer];
}

#pragma mark
#pragma mark - 添加转场动画
- (void)makeTransition{
    
    CATransition *transition = [CATransition animation];
    transition.type = @"cube";
    transition.subtype = kCATransitionFromRight;
    transition.duration = 1;
    
    [self.imageUCV.layer addAnimation:transition forKey:nil];
    
}
@end
